<template>
    <view class="chatInterface">
        <view class="scroll-view" @tap="dianji">
            <view class="all-history-loaded">
                {{allHistoryLoaded ? '已经没有更多的历史消息' : '下拉获取历史消息'}}
            </view>
            <checkbox-group @change="selectMessages">
                <!--消息记录-->
                <view v-for="(message,index) in messages" :key="message.messageId">
                    <!--时间显示，类似于微信，隔5分钟不发言，才显示时间-->
                    <view class="time-lag">
                        {{renderMessageDate(message, index)}}
                    </view>
                    <view class="message-recalled" v-if="message.recalled">
                        <view v-if="message.senderId !== currentUser.id">{{friend.name}}撤回了一条消息</view>
                        <view v-else class="message-recalled-self">
                            <view>你撤回了一条消息</view>
                            <span v-if="message.type === 'text' && Date.now()-message.timestamp< 60 * 1000 "
                                @click="editRecalledMessage(message.payload.text)">重新编辑</span>
                        </view>
                    </view>
                    <view class="message-item" v-else>
                        <view class="message-item-checkbox">
                            <checkbox v-show="messageSelector.visible && message.status !== 'sending'"
                                :value="message.messageId" :checked="messageSelector.messages.includes(message)" />
                        </view>
                        <view class="message-item-content" :class="{'self' : message.senderId ===  currentUser.id}">
                            <view class="avatar">
                                <image @click="leftAvatarClick(message.senderId)" style="border-radius: 10rpx;"
                                    :src="message.senderId === currentUser.id? currentUser.avatar : friend.avatar">
                                </image>
                            </view>
                            <view class="content" @longpress="showActionPopup(message)">
                                <view class="message-payload">
                                    <b class="pending" v-if="message.status === 'sending'"></b>
                                    <b class="send-fail" v-if="message.status === 'fail'"></b>
                                    <view v-if="message.type === 'text'" class="text-content">{{message.payload.text}}
                                    </view>
                                    <view v-if="message.type === 'voiceCancel'" class="text-content"
                                        style="display: flex; align-items: center;">
                                        {{message.payload}}
                                        <image style="width: 50rpx;height: 50rpx; margin-left: 15rpx;"
                                            :src="message.senderId ===  currentUser.id?'/static/gua1.png':'/static/guaduan.png'">
                                        </image>
                                    </view>
                                    <view v-if="message.type === 'voiceTime'" class="text-content"
                                        style="display: flex; align-items: center;">
                                        {{message.payload}}
                                        <image style="width: 50rpx;height: 50rpx; margin-left: 15rpx;"
                                            :src="message.senderId ===  currentUser.id?'/static/gua1.png':'/static/guaduan.png'">
                                        </image>
                                    </view>
                                    <image class="image-content" v-if="message.type === 'image'"
                                        :src="message.payload.url" :data-url="message.payload.url"
                                        @click="showImageFullScreen" mode="widthFix"></image>
                                    <view class="video-snapshot" v-if="message.type === 'video'"
                                        :data-url="message.payload.video.url" @click="playVideo">
                                        <image :src="message.payload.thumbnail.url" mode="aspectFit"></image>
                                        <view class="video-play-icon"></view>
                                    </view>
                                    <image class="image-content" v-if="message.type === 'emoji'" :src="message.payload">
                                    </image>
                                    <!-- 视频 -->
                                    <GoEasyAudioPlayer v-if="message.type ==='audio'" :src="message.payload.url"
                                        :duration="message.payload.duration" />
                                    <!-- 红包 -->
                                    <view v-if="message.type=='redpacket' " @tap='redpack_open(message)'
                                        :class="{'redpack':true,'redpack-open':message.payload.content.isopen==1}"
                                        @longtap="msgAction($event,message)">
                                        <view class="info">
                                            <block v-if="message.senderId==currentUser.id">
                                                <view class="icon">
                                                    <image
                                                        :src="message.payload.content.isopen==1?'/static/img/redpackopen-icon.png':'/static/img/redpack-icon.png'">
                                                    </image>
                                                </view>
                                                <view class="showtext">{{message.payload.content.title}}</view>

                                            </block>

                                            <block v-else>
                                                <view class="icon">
                                                    <image
                                                        :src="message.payload.content.isopen==1?'/static/img/redpackopen-icon.png':'/static/img/redpack-icon.png'">
                                                    </image>
                                                </view>
                                                <view class="showtext">{{message.payload.content.title}}</view>
                                            </block>

                                        </view>
                                        <view class="title" style="text-align: right;padding-right: 20rpx;">
                                            {{isType[message.payload.content.type]}}
                                        </view>
                                    </view>
                                </view>
                                <view v-if="message.senderId === currentUser.id&&message.type!='redpacket'"
                                    :class="message.read ?'message-read':'message-unread'">
                                    <view v-if="message.status === 'success'">{{message.read?'已读':'未读'}}</view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </checkbox-group>
        </view ref="scrollView">
        <view class="action-box" v-if="!videoPlayer.visible && !messageSelector.visible">
            <view class="action-top" style="display: flex;align-items: center;justify-content: space-between;">
                <view class="emoji" style="width: 12%;text-align: center;" @click="switchAudioKeyboard">
                    <text style="font-size: 31px;"
                        :class="[audio.visible ? 'n-icon n-icon-keyboard':'n-icon n-icon-voice']"
                        class="n-icon n-icon-voice"></text>
                </view>
                <view class="record-input" @touchstart="onRecordStart" @touchend="onRecordEnd" v-if="audio.visible">
                    {{audio.recording ? '松开发送' : '按住录音'}}
                </view>
                <view class="message-input" :style="content?'width: 60%;':'width: 65%;'" v-else>
                    <!-- GoEasyIM最大支持3k的文本消息，如需发送长文本，需调整输入框maxlength值 -->
                    <input style="width: 95%;" type="text" maxlength="1000" placeholder="发送消息" v-model="content"
                        @focus="messageInputFocusin">
                </view>
                <view :style="content?'width: 26%;':'width: 21%;'" style="display: flex;align-items: center; ">
                    <view style="font-size: 31px;margin-bottom: 5rpx;"
                        :class="emoji.visible?'n-icon-keyboard':'n-icon-face'" class="n-icon n-icon-face"
                        @click="showEmoji"></view>
                    <view class="emoji" style="margin-left: 15rpx;" @click="showOtherTypesMessagePanel" v-if="!content">
                        <text style="font-size: 37px;color: #444; ">
                            {{otherTypesMessagePanelVisible?'&#xe603;':'&#xe634;'}}</text>
                    </view>
                    <view class="btn sendbtn" v-if="content" @touchend.prevent="createTextMessage">发送</view>
                </view>
            </view>
            <!--展示表情列表-->
            <view class="action-bottom " v-if="emoji.visible">
                <!-- <image class="emoji-item" v-for="(emojiItem, emojiKey, index) in emoji.map" :key="index" :src="emoji.url + emojiItem" @click="chooseEmoji(emojiKey)"></image> -->
                <scroller class="scroller">
                    <div append="tree" class="emoj_box">
                        <block v-for="(item,index) in emojiList" :key="index">
                            <text @click="setEmoj(item,index)" class="emoj_box_img">{{item}}</text>
                        </block>
                    </div>
                </scroller>
            </view>
            <!-- 表情包图片 -->
            <view class="action-bottom " v-if="biaoFalse">
                <scroller class="scroller">
                    <div append="tree" class="emoj_box">
                        <block v-for="(item,index) in biaoList" :key="index">
                            <image @click="handleEmotionbiaoFalse(item)"
                                style="margin: 5rpx; width: 110rpx;height: 110rpx;"
                                :src="`https://de-a.nextapi.cc`+item"></image>
                        </block>
                    </div>
                </scroller>
            </view>
            <!--其他类型消息面板-->
            <view class="action-bottom" style="display: flex;flex-wrap: wrap;" v-if="otherTypesMessagePanelVisible">
                <view class="more-item" @click="createImageMessage">
                    <image style="width: 70rpx;height: 70rpx;" src="../../../static/aa/tu.png"></image>
                    <text>图片</text>
                </view>
                <view class="more-item" @click="createVideoMessage">
                    <image style="width: 70rpx;height: 70rpx;" src="../../../static/aa/pa.png"></image>
                    <text>视频</text>
                </view>
                <view class="more-item" style="padding-top: 2rpx;" @tap="getCall">
                    <image style="width: 70rpx;height: 70rpx;" src="../../../static/aa/yu.png"></image>
                    <text style="margin-top: 5rpx;">通话</text>
                </view>
                <view class="more-item" @click="biao">
                    <image style="width: 70rpx;height: 70rpx;" src="../../../static/aa/bao.png"></image>
                    <text>表情包</text>
                </view>
                <view class="more-item" @click="hongbao">
                    <image style="width: 70rpx;height: 70rpx;" src="../../../static/aa/hh.png"></image>
                    <text>发红包</text>
                </view>
                <view class="more-item" @click="shoucang">
                    <image style="width: 70rpx;height: 70rpx;" src="../../../static/aa/cang.png"></image>
                    <text>收藏</text>
                </view>
                <view class="more-item" style="padding-top: 10rpx;" @click="wen">
                    <image style="width: 60rpx;height: 60rpx;" src="../../../static/aa/wen.png"></image>
                    <text>文件</text>
                </view>

            </view>
        </view>
        <view class="action-popup" @touchmove.stop.prevent v-if="actionPopup.visible">
            <view class="layer"></view>
            <view class="action-box">
                <view class="action-item" @click="deleteSingleMessage">删除</view>
                <view class="action-item" v-if="actionPopup.recallable" @click="recallMessage">撤回</view>
                <view class="action-item" @click="showCheckBox">多选</view>
                <view class="action-item" @click="actionPopup.visible = false">取消</view>
            </view>
        </view>
        <view class="messageSelector-box" v-if="messageSelector.visible">
            <image class="messageSelector-btn" @click="deleteMultipleMessages" src="/static/images/delete.png"></image>
        </view>
        <redpick v-if="is_redpack_open" :item="redpack_info" @closePick="is_redpack_open=false;"
            @fresmsg="freshmsg_fromredopen"></redpick>
        <view class="record-loading" v-if="audio.recording"></view>
        <video v-if="videoPlayer.visible" :src="videoPlayer.url" id="videoPlayer"
            @fullscreenchange="onVideoFullScreenChange"></video>
    </view>
</template>

<script>
    import GoEasyAudioPlayer from '../../../components/GoEasyAudioPlayer/GoEasyAudioPlayer';
    import EmojiDecoder from '../../../lib/EmojiDecoder';
    import restApi from '../../../lib/restapi';
    const recorderManager = uni.getRecorderManager();
    import emojix from '@/components/chat-list/bottom-input/minxi/emoji.js'
    import http from '@/library/http.js';
    import redpick from '@/components/get-redpick.vue'
    import api from "@/library/index.js"

    const GoEasy = uni.$GoEasy;
    const GRTC = uni.$GRTC;
    
    export default {
        name: 'privateChat',
        components: {
            GoEasyAudioPlayer,
            redpick
        },
        data() {

            return {
                //聊天文本框
                content: '',
                friend: null,
                currentUser: uni.getStorageSync('userInfo'),
                //消息记录
                messages: [],
                //是否加载完所有历史消息
                allHistoryLoaded: false,

                //定义表情列表
                emoji: {
                    visible: false,
                },
                //是否展示‘其他消息类型面板’
                otherTypesMessagePanelVisible: false,
                audio: {
                    startTime: null,
                    //语音录音中
                    recording: false,
                    //录音按钮展示
                    visible: false
                },

                videoPlayer: {
                    visible: false,
                    url: '',
                    context: null
                },
                // 展示自定义消息框
                customMessageFormVisible: false,

                // 展示消息删除弹出框
                actionPopup: {
                    visible: false,
                    message: null,
                    recallable: false,
                },
                // 消息选择
                messageSelector: {
                    visible: false,
                    messages: []
                },
                emojiList: [],
                text: '',
                biaoFalse: false,
                //键盘高度
                keyboardHeight: 0,
                //底部消息发送高度
                bottomHeight: 0,
                biaoList: [
                    // '/uploads/images/gif/1.gif',
                    '/uploads/images/gif/3.gif',
                    '/uploads/images/gif/4.gif',
                    '/uploads/images/gif/6.gif',
                    '/uploads/images/gif/7.gif',
                    '/uploads/images/gif/8.jpg',
                    '/uploads/images/gif/9.gif',
                    '/uploads/images/gif/10.gif',
                    '/uploads/images/gif/11.gif',
                    '/uploads/images/gif/12.gif',
                    '/uploads/images/gif/13.gif',
                    '/uploads/images/gif/14.gif',
                    '/uploads/images/gif/16.gif',
                    '/uploads/images/gif/17.gif',
                    '/uploads/images/gif/18.gif',
                    '/uploads/images/gif/19.gif',
                    '/uploads/images/gif/20.jpg',
                    '/uploads/images/gif/21.gif',
                    '/uploads/images/gif/22.gif',
                    '/uploads/images/gif/23.jpg',
                    '/uploads/images/gif/24.jpg',
                    '/uploads/images/gif/25.gif',
                    '/uploads/images/gif/26.jpg',
                    '/uploads/images/gif/27.jpg',
                    '/uploads/images/gif/28.jpg',
                    '/uploads/images/gif/29.jpg',
                    '/uploads/images/gif/30.jpg',
                    '/uploads/images/gif/32.gif',
                    '/uploads/images/gif/33.gif',
                    '/uploads/images/gif/34.jpg',
                    '/uploads/images/gif/35.gif',
                    '/uploads/images/gif/36.gif',
                    '/uploads/images/gif/37.gif',
                    '/uploads/images/gif/38.gif',
                    '/uploads/images/gif/39.gif',
                    '/uploads/images/gif/40.gif',
                    '/uploads/images/gif/41.gif',
                    '/uploads/images/gif/42.gif',
                    '/uploads/images/gif/43.gif',
                    '/uploads/images/gif/44.jpg',
                    '/uploads/images/gif/45.jpg',
                    '/uploads/images/gif/46.gif',
                    '/uploads/images/gif/47.gif',
                    '/uploads/images/gif/48.gif'
                ],
                is_redpack_open: false,
                redpack_info: {},
                clickIndex: 0

            }
        },
        computed: {
            isType() {
                return {
                    1: '手气红包',
                    2: '红包',
                    3: '专属红包',
                    4: '口令红包'
                }
            },
            windowHeight() {
                return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
            },
            inputHeight() {
                return this.bottomHeight + this.keyboardHeight
            }

        },

        onReady() {
            this.videoPlayer.context = uni.createVideoContext('videoPlayer', this);
        },
        onShow() {
            this.otherTypesMessagePanelVisible = false;
            this.emoji.visible = false;
            this.getuserinfodes()
        },
        created() {
            this.emojiList = emojix
        },
        onLoad(options) {
            console.log('dadadasdadasda', options)
            this.text = options.nickname
            //聊天对象
            let friendId = options.id;
            this.friend = options
            this.initialGoEasyListeners();
            this.loadHistoryMessage(true);
            // 录音监听器
            this.initRecorderListeners();
            this.getUserInfo(friendId)

            //从服务器获取最新的好友信息


            this.getMsgInfo(0)

            uni.onKeyboardHeightChange(res => {
                //这里正常来讲代码直接写
                //this.keyboardHeight=this.rpxTopx(res.height)就行了
                //但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
                this.keyboardHeight = this.rpxTopx(res.height - 30)
                if (this.keyboardHeight < 0) this.keyboardHeight = 0;
            })

        },
        onPullDownRefresh(e) {
            this.loadHistoryMessage(false);
        },
        onUnload() {
            //退出聊天页面之前，清空监听器
            GoEasy.im.on(this.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, () => {});
            GoEasy.im.on(this.GoEasy.IM_EVENT.MESSAGE_DELETED, () => {});
            uni.offKeyboardHeightChange()
        },
        onNavigationBarButtonTap(e) {
            uni.navigateTo({
                url: '/pages/friend/userset?id=' + this.friend.id + '&status=friend'
            })
            return
        },
        methods: {
            // px转换成rpx
            rpxTopx(px) {
                let deviceWidth = wx.getSystemInfoSync().windowWidth
                let rpx = (750 / deviceWidth) * Number(px)
                return Math.floor(rpx)
            },

            getMSGlIST(user) {
                let list = uni.getStorageSync('CallData')
                console.log('看看是否为空', list)
                if (list.length <= 0) {

                } else {
                    list.forEach((item, index) => {
                        if (item.userId == user.userId) {
                            console.log('则不加缓存')
                            return
                        } else {
                            list.push(user)
                            uni.setStorageSync('CallData', list)
                            console.log('否则加入缓存', uni.getStorageSync('CallData'))
                        }
                    })
                }

            },
            yuyins(message) {
                const currentCall = GRTC.currentCall();

                let imageMessage = GoEasy.im.createCustomMessage({
                    to: {
                        id: currentCall.user.id,
                        type: GoEasy.IM_SCENE.PRIVATE,
                        data: {
                            name: currentCall.user.data.name,
                            avatar: currentCall.user.data.avatar
                        }
                    },
                    type: 'voiceCancel',
                    payload: message,
                    onProgress: function(progress) {
                        console.log('大苏打大', progress)
                    },
                    notification: {
                        title: '发来一条语音消息',
                        body: '[语音消息]',
                        badge: '+1' // 字段最长 50 字符
                    }
                });
                this.sendMessage(imageMessage);
            },
            freshmsg_fromredopen(e) {
                this.initialGoEasyListeners();
            },
            redpack_open(m) {
                console.log('redpack_open', m)
                switch (m.payload.content.type) {
                    case '1':
                        this.getSendPay(m)
                        break;
                    case '2':
                        this.getSendPay(m)
                        break;
                    case '3':
                        this.getSendPay(m)
                        break;
                    case '4':
                        this.redkou_open(m)
                        break;

                }
            },
            // 口令红包
            redkou_open(m) {
                uni.showModal({
                    title: '口令',
                    content: '',
                    editable: true, //是否显示输入框
                    placeholderText: '请输入口令', //输入框提示内容
                    confirmText: '确认',
                    cancelText: '取消',
                    success: (res) => {
                        if (res.confirm) {
                            console.log('输入的内容：', res.content, m);
                            if (!res.content) {
                                return uni.showToast({
                                    title: '请输入口令',
                                    icon: 'none'
                                })
                            }
                            if (m.payload.content.isopen != 0) {
                                uni.navigateTo({
                                    url: '../friend/redpacket_detail?msg_id=' + m.msg_id +
                                        '&storekey=' + m.cache_key + '&content=' + res.content
                                })
                            } else {
                                m.command = res.content
                                console.log('输入的内容：', m);
                                let dat = {
                                    sender: {
                                        nickname: this.currentUser.nickname,
                                        avatar: this.currentUser.avatar,
                                    },
                                    message: m.payload
                                }
                                this.kou_open(dat, res.content)

                            }
                        }
                    }
                })
            },
            kou_open(item, command) {

                this.redpack_info = item.message.content;
                this.redpack_info.content = item.message.content
                var postdata = {
                    userid: this.currentUser.id,
                    id: item.message.content.id,
                    command: command
                }

                http.setWait(false).post('group.php?act=get_redpacket', postdata).then(res => {

                    if (res.code == 200) {
                        // this.getover(res.data);
                        uni.showToast({
                            title: '领取成功',
                            icon: 'none'
                        })
                    } else {
                        clearInterval(this.timer)
                        uni.showToast({
                            title: '网络异常，请稍后再试',
                            icon: 'none'
                        })
                    }

                })
            },
            getSendPay(m) {
                if (m.payload.content.isgroup != 0 && m.payload.content.type != 3 && m.payload.content.isopen == 1) {
                    uni.navigateTo({
                        url: '../friend/redpacket_detail?msg_id=' + m.friend_uid
                    })
                } else {
                    let dat = {
                        sender: {
                            nickname: this.currentUser.nickname,
                            avatar: this.currentUser.avatar,
                        },
                        message: m.payload
                    }
                    this.redpack_info = dat
                    this.is_redpack_open = true;
                }
            },
            msgAction(e, m) {
                console.log('点击领取红包', e, m)
            },
            ceshi(order) {
                let imageMessage = this.goEasy.im.createCustomMessage({
                    to: {
                        id: this.friend.id,
                        type: this.GoEasy.IM_SCENE.PRIVATE,
                        data: {
                            name: this.friend.nickname,
                            avatar: this.friend.avatar
                        }
                    },
                    type: 'redpacket',
                    payload: order,
                    onProgress: function(progress) {
                        console.log(progress)
                    },
                    notification: {
                        title: this.currentUser.nickname + '发来一张表情',
                        body: '[表情]',
                        badge: '+1' // 字段最长 50 字符
                    }
                });
                this.sendMessage(imageMessage);
            },
            // 点击选择表情图片
            handleEmotionbiaoFalse(item) {
                console.log('点击选择表情图片', item)
                let imageMessage = this.goEasy.im.createCustomMessage({
                    to: {
                        id: this.friend.id,
                        type: this.GoEasy.IM_SCENE.PRIVATE,
                        data: {
                            name: this.friend.nickname,
                            avatar: this.friend.avatar
                        }
                    },
                    type: 'emoji',
                    payload: `https://de-a.nextapi.cc${item}`,
                    onProgress: function(progress) {
                        console.log(progress)
                    },
                    notification: {
                        title: this.currentUser.nickname + '发来一张表情',
                        body: '[表情]',
                        badge: '+1' // 字段最长 50 字符
                    }
                });
                this.sendMessage(imageMessage);
            },
            // 点击关闭
            dianji() {
                this.biaoFalse = false
                this.emoji.visible = false
                this.otherTypesMessagePanelVisible = false
            },
            setEmoj(item, index) {
                this.content += item
            },
            // 左测消息，头像点击
            leftAvatarClick(item) {
                console.log('左测消息，头像点击')
                console.log(item)
                uni.navigateTo({
                    url: '/pages/friend/detail?id=' + item
                })
            },
            rightAvatarClick(item) {
                console.log('右侧测消息，头像点击')
                uni.navigateTo({
                    url: '/pages/friend/detail?id=' + item.id
                })
            },
            // 表情
            biao() {
                this.biaoFalse = true
                this.emoji.visible = false
                this.otherTypesMessagePanelVisible = false
            },
            // 文件
            wen() {
                let chooseFileModule = uni.requireNativePlugin("Rc-ChosseFile_ChooseFileModule");
                chooseFileModule.openFileBrowse()
            },
            //发红包
            hongbao() {

                if (this.currentUser.banknum < 1) {
                    uni.showModal({
                        title: '提示',
                        // content: "绑定SK账号后才可以发送红包",
                        content: "绑定银行账号后才可以发送红包",
                        showCancel: true,
                        cancelText: '关闭',
                        confirmText: '立即绑定',
                        success: res => {
                            if (res.confirm) {
                                uni.navigateTo({
                                    url: "/pages/mine/bank"
                                })
                            }
                        }
                    });
                    return false;
                } else {
                    this.otherTypesMessagePanelVisible = false
                    uni.navigateTo({
                        url: '/pages/friend/readpacket?isgroup=0' + '&id=' + this.friend.id
                    })
                }
            },
            //收藏
            shoucang() {
                uni.navigateTo({
                    url: '/pages/friend/shoucang/shoucang'
                })
            },
            //通话
            getCall() {
                let _this = this;
                this.clickIndex = this.clickIndex + 1
                console.log('判断点击了几次通话', this.clickIndex)
                if (this.clickIndex == 1) {

                   setTimeout(() => {
                       GRTC.call({
                           calleeId: this.friend.id,
                           mediaType: 0,
                           notification: {
                               title: this.currentUser.nickname,
                               body: '邀请你语音通话',
                               sound: 'ring',
                               badge: '+1'
                           },
                       }).then(() => {
                           console.log('打印阿达的', this.friend.id)
                           this.clickIndex = 0
                           uni.navigateTo({
                               url: `/pages/rtc/private/dial?id=` + _this.friend.id + '&nickname=' + this
                                   .friend.nickname + '&avatar=' + this.friend.avatar,
                           })
                       }).catch((error) => {
                           console.log('报错',error)
                           GRTC.end()
                           uni.showToast({
                               icon: "none",
                               title: '对方忙线中',
                               duration: 2000
                           })
                       })
                   },600)

                } else {
                    GRTC.end()
                    this.clickIndex = 0
                }
            },
            getuserinfodes() {
                var postdata = {
                    id: uni.getStorageSync('access_token')
                };
                http.setWait(false).post('user.php?act=userinfo', postdata).then(res => {
                    this.currentUser = res.data;
                    uni.setStorageSync('userInfo', this.currentUser)
                })

            },
            getUserInfo(id) {
                id = parseInt(id);
                console.log('dadasdadadsada', Number(id), this.currentUser)
                http.setWait(false).get('user.php?act=userdetail', {
                    id: id,
                    group_id: 0,
                    userid: this.currentUser.id
                }).then(res => {
                    this.friend = res.data;
                    this.text = this.friend.nickname + `(${this.friend.isonline == 1?'在线':'离线'})`
                    uni.setNavigationBarTitle({
                        title: this.text
                    });
                }).catch(() => {
                    uni.setNavigationBarTitle({
                        title: `${this.text}(离线')`
                    });
                })
            },
            //渲染文本消息，如果包含表情，替换为图片
            //todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
            renderTextMessage(message) {
                return '<span class="text-content">' + this.emoji.decoder.decode(message.payload.text) + '</span>'
            },
            //像微信那样显示时间，如果有几分钟没发消息了，才显示时间
            //todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
            renderMessageDate(message, index) {
                if (index === 0) {
                    return this.formatDate(message.timestamp)
                } else {
                    if (message.timestamp - this.messages[index - 1].timestamp > 5 * 60 * 1000) {
                        return this.formatDate(message.timestamp)
                    }
                }
                return '';
            },
            initialGoEasyListeners() {
                // 监听私聊消息
                this.goEasy.im.on(this.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, (message) => {
                    console.log('PRIVATE_MESSAGE_RECEIVED:', message);
                    let senderId = message.senderId;
                    let receiverId = message.receiverId;
                    let friendId = this.currentUser.id === senderId ? receiverId : senderId;
                    if (friendId === this.friend.id) {
                        this.messages.push(message);
                        //聊天时，收到消息标记为已读
                        this.markPrivateMessageAsRead();
                        //收到新消息，是滚动到最底部
                        this.scrollToBottom();
                    }
                });
                //监听消息删除
                this.goEasy.im.on(this.GoEasy.IM_EVENT.MESSAGE_DELETED, (deletedMessages) => {
                    deletedMessages.forEach(message => {
                        let senderId = message.senderId;
                        let receiverId = message.receiverId;
                        let friendId = this.currentUser.id === senderId ? receiverId : senderId;
                        if (friendId === this.friend.id) {
                            let index = this.messages.indexOf(message);
                            if (index > -1) {
                                this.messages.splice(index, 1);
                            }
                        }
                    });
                });
            },
            initRecorderListeners() {
                // 监听录音开始
                recorderManager.onStart(() => {
                    this.audio.recording = true;
                    this.audio.startTime = Date.now();
                });
                //录音结束后，发送
                recorderManager.onStop((res) => {
                    let endTime = Date.now();
                    this.audio.recording = false;
                    let duration = endTime - this.audio.startTime;
                    if (duration < 1000) {
                        uni.showToast({
                            icon: 'error',
                            title: '录音时间太短',
                            duration: 500
                        });
                        return;
                    }
                    res.duration = duration;
                    let audioMessage = this.goEasy.im.createAudioMessage({
                        to: {
                            id: this.friend.id,
                            type: this.GoEasy.IM_SCENE.PRIVATE,
                            data: {
                                name: this.friend.nickname,
                                avatar: this.friend.avatar
                            }
                        },
                        file: res,
                        onProgress: function(progress) {
                            console.log(progress)
                        },
                        notification: {
                            title: this.currentUser.nickname + '发来一段语音',
                            body: '[语音消息]',
                            badge: '+1' // 字段最长 50 字符
                        }
                    });
                    this.sendMessage(audioMessage);
                });
                // 监听录音报错
                recorderManager.onError((res) => {
                    this.audio.recording = false;
                    recorderManager.stop();
                    uni.showToast({
                        icon: 'none',
                        title: '录音失败,请检查麦克风权限',
                        duration: 1000
                    });
                })
            },
            sendMessage(message) {
                console.log('们所打动', message)
                this.messages.push(message);
                this.scrollToBottom();
                
                let that = this
                
                var mid =  'm' + Math.random().toString(36).substring(2);
                let data = {
                    userid: message.senderId,
                    friend_uid: message.receiverId,
                    type: 'chat',
                    msgtype: message.type,
                    content: message.type == 'text'?message.payload.text:message,
                    mid: 'm' + Math.random().toString(36).substring(2)
                };
                this.goEasy.im.sendMessage({
                    message: message,
                    onSuccess: function(message) {
                        console.log('发送成功.', message);
                        // that.getMsg(tps)
                        that.$socket.send(data);
                        
                    },
                    onFailed: function(error) {
                        if (error.code === 507) {
                            console.log(
                                '发送语音/图片/视频/文件失败，没有配置OSS存储，详情参考：https://docs.goeasy.io/2.x/im/message/media/alioss'
                            );
                        } else {
                            console.log('发送失败:', error);
                        }
                    }
                });
                this.goEasy.pubsub.publish({
                    channel: message.receiverId,  //请确认与接收端一致
                    message: message.payload.text,
                    qos: 1,//app内onMessage收到的消息内容
                    notification: { //定义通知栏推送
                        title: '您有一条新消息', //通知栏提醒标题，仅显示于通知栏
                        body: message.payload.text, //通知栏提醒内容，仅显示于通知栏
                        badge: "+1", //角标，值必须有引号，"0"表示该消息不需要设置角标，"+1"表示角标+1，不支持其他值， 默认为“0”
                    },
                    onSuccess: function () {
                        console.log("推送消息时设置角标 successfully.")
                    },
                    onFailed: function (error) {
                        console.log("推送消息时设置角标 to publish message, code:" + error.code + ' error:' + error.content);
                    }
                });
            },
            //获取云端消息记录
            async getMsgInfo(totime) {
                if (totime < 1) {
                    var isfrist = true;
                    totime = parseInt((new Date()).getTime() / 1000);
                }
                var postdata = {
                    id: parseInt(this.friend.id),
                    userid: parseInt(this.currentUser.id),
                    isgroup: 0,
                    totime: totime
                };
                const {
                    data
                } = await http.setWait(false).get('group.php?act=messages2', postdata)
                console.log('这是聊天记录', data)
            },
            getMsg(msg) {
                msg = JSON.parse(msg)
                console.log(msg.type)
                api.postMsg({
                    userid: this.currentUser.id,
                    friend_uid: this.friend.id,
                    type: 'chat',
                    msgtype: msg.type,
                    groupid: '',
                    content: '888888'
                }).then(res => {
                    this.getMsgInfo(0)
                    console.log('发送消息成功---', res)
                })
            },
            createTextMessage() {
                if (this.content.trim() !== '') {
                    this.emoji.visible = false
                    let body = this.content;
                    if (this.content.length >= 50) {
                        body = this.content.substring(0, 30) + '...';
                    }
                    let textMessage = this.goEasy.im.createTextMessage({
                        text: this.content,
                        to: {
                            id: this.friend.id,
                            type: this.GoEasy.IM_SCENE.PRIVATE,
                            data: {
                                name: this.friend.nickname,
                                avatar: this.friend.avatar
                            }
                        },
                        notification: {
                            title: this.currentUser.nickname + '发来一段文字',
                            body: body,
                            badge: '+1'
                        }
                    });
                    this.sendMessage(textMessage);
                }
                this.content = '';
            },
            showActionPopup(message) {
                const MAX_RECALLABLE_TIME = 3 * 60 * 1000; //3分钟以内的消息才可以撤回
                this.messageSelector.messages = [message];
                if ((Date.now() - message.timestamp) < MAX_RECALLABLE_TIME && message.senderId === this.currentUser
                    .id && message.status === 'success') {
                    this.actionPopup.recallable = true;
                } else {
                    this.actionPopup.recallable = false;
                }
                this.actionPopup.visible = true;
            },
            deleteSingleMessage() {
                uni.showModal({
                    content: '确认删除？',
                    success: (res) => {
                        this.actionPopup.visible = false;
                        if (res.confirm) {
                            this.deleteMessage();
                        }
                    },
                })
            },
            deleteMultipleMessages() {
                if (this.messageSelector.messages.length > 0) {
                    uni.showModal({
                        content: '确认删除？',
                        success: (res) => {
                            this.messageSelector.visible = false;
                            if (res.confirm) {
                                this.deleteMessage();
                            }
                        },
                    })
                }
            },
            deleteMessage() {
                this.goEasy.im.deleteMessage({
                    messages: this.messageSelector.messages,
                    onSuccess: (result) => {
                        this.messageSelector.messages.forEach(message => {
                            let index = this.messages.indexOf(message);
                            if (index > -1) {
                                this.messages.splice(index, 1);
                            }
                        });
                        this.messageSelector.messages = [];
                    },
                    onFailed: (error) => {
                        console.log('error:', error);
                    }
                });
            },
            // 消息撤回
            recallMessage() {
                this.actionPopup.visible = false;
                this.goEasy.im.recallMessage({
                    messages: this.messageSelector.messages,
                    onSuccess: () => {
                        console.log('撤回成功');
                    },
                    onFailed: (error) => {
                        console.log('撤回失败,error:', error);
                    }
                });
            },
            editRecalledMessage(content) {
                if (this.audio.visible) {
                    this.audio.visible = false;
                }
                this.content = content;
            },
            showCheckBox() {
                this.messageSelector.messages = [];
                this.messageSelector.visible = true;
                this.actionPopup.visible = false;
            },
            selectMessages(e) {
                const selectedMessageIds = e.detail.value;
                let selectedMessages = [];
                this.messages.forEach(message => {
                    if (selectedMessageIds.includes(message.messageId)) {
                        selectedMessages.push(message);
                    }
                })
                this.messageSelector.messages = selectedMessages;
            },
            loadHistoryMessage(scrollToBottom) { //历史消息
                let lastMessageTimeStamp = null;
                let lastMessage = this.messages[0];
                if (lastMessage) {
                    lastMessageTimeStamp = lastMessage.timestamp;
                }
                this.goEasy.im.history({
                    userId: this.friend.id,
                    lastTimestamp: lastMessageTimeStamp,
                    limit: 100,
                    onSuccess: (result) => {
                        console.log("result:", result);
                        uni.stopPullDownRefresh();
                        let messages = result.content;
                        if (messages.length === 0) {
                            this.allHistoryLoaded = true;
                        } else {
                            this.messages = messages.concat(this.messages);
                            if (scrollToBottom) {
                                this.scrollToBottom();
                                //收到的消息设置为已读
                                this.markPrivateMessageAsRead();
                            }
                        }
                    },
                    onFailed: (error) => {
                        //获取失败
                        console.log('获取历史消息失败:', error);
                        uni.stopPullDownRefresh();
                    }
                });
            },
            //语音录制按钮和键盘输入的切换
            switchAudioKeyboard() {
                this.audio.visible = !this.audio.visible;
                if (uni.authorize) {
                    uni.authorize({
                        scope: 'scope.record',
                        fail: () => {
                            uni.showModal({
                                title: '获取录音权限失败',
                                content: '请先授权才能发送语音消息！'
                            });
                        }
                    });
                }
            },
            onRecordStart() {
                try {
                    recorderManager.start();
                } catch (e) {
                    uni.showModal({
                        title: '录音错误',
                        content: '录音错误'
                    });
                }
            },
            onRecordEnd() {
                try {
                    recorderManager.stop();
                } catch (e) {
                    console.log(e);
                }
            },
            createVideoMessage() {
                uni.chooseVideo({
                    success: (res) => {
                        let videoMessage = this.goEasy.im.createVideoMessage({
                            to: {
                                id: this.friend.id,
                                type: this.GoEasy.IM_SCENE.PRIVATE,
                                data: {
                                    name: this.friend.nickname,
                                    avatar: this.friend.avatar
                                }
                            },
                            file: res,
                            onProgress: function(progress) {
                                console.log(progress)
                            },
                            notification: {
                                title: this.currentUser.nickname + '发来一个视频',
                                body: '[视频消息]',
                                badge: '+1' // 字段最长 50 字符
                            }
                        });
                        this.sendMessage(videoMessage);
                    }
                })
            },
            createImageMessage() {
                uni.chooseImage({
                    count: 9,
                    success: (res) => {
                        res.tempFiles.forEach(file => {
                            let imageMessage = this.goEasy.im.createImageMessage({
                                to: {
                                    id: this.friend.id,
                                    type: this.GoEasy.IM_SCENE.PRIVATE,
                                    data: {
                                        name: this.friend.nickname,
                                        avatar: this.friend.avatar
                                    }
                                },
                                file: file,
                                onProgress: function(progress) {
                                    console.log(progress)
                                },
                                notification: {
                                    title: this.currentUser.nickname + '发来一张图片',
                                    body: '[图片消息]',
                                    badge: '+1' // 字段最长 50 字符
                                }
                            });
                            this.sendMessage(imageMessage);
                        })
                    }
                });
            },
            showImageFullScreen(e) {
                let imagesUrl = [e.currentTarget.dataset.url];
                uni.previewImage({
                    urls: imagesUrl
                });
            },
            playVideo(e) {
                this.videoPlayer.visible = true;
                this.videoPlayer.url = e.currentTarget.dataset.url;
                this.$nextTick(() => {
                    this.videoPlayer.context.requestFullScreen({
                        direction: 0
                    });
                    this.videoPlayer.context.play();
                });
            },
            onVideoFullScreenChange(e) {
                //当退出全屏播放时，隐藏播放器
                if (this.videoPlayer.visible && !e.detail.fullScreen) {
                    this.videoPlayer.visible = false;
                    this.videoPlayer.context.stop();
                }
            },
            messageInputFocusin() {
                this.otherTypesMessagePanelVisible = false;
                this.emoji.visible = false;
            },
            showEmoji() {
                this.emoji.visible = !this.emoji.visible;
                this.otherTypesMessagePanelVisible = false;
                this.biaoFalse = false
            },
            showOtherTypesMessagePanel() {
                this.otherTypesMessagePanelVisible = !this.otherTypesMessagePanelVisible;
                this.emoji.visible = false;
                this.biaoFalse = false
            },
            chooseEmoji(emojiKey) {
                this.content += emojiKey;
            },

            showCustomMessageForm() {
                this.customMessageFormVisible = true;
            },
            closeCustomMessageForm() {
                this.customMessageFormVisible = false;
            },
            scrollToBottom() {
                setTimeout(() => {
                    uni.pageScrollTo({
                        scrollTop: 2000000,
                        duration: 0
                    })
                }, 500);
            },
            markPrivateMessageAsRead() {
                this.goEasy.im.markPrivateMessageAsRead({
                    userId: this.friend.id,
                    onSuccess: function() {
                        console.log('标记私聊已读成功');
                    },
                    onFailed: function(error) {
                        console.log("标记私聊已读失败", error);
                    }
                });
            },
            onNavigationBarButtonTap() {
                // this.$refs.panel.endVedio();
                this.$jump('group.detail', {
                    id: this.group.id,
                    'from': 'chat'
                });

            }
        }
    }
</script>

<style lang="scss" scoped>
    $redpackBgColor: #fa8d34;
    $control-height: 120upx;
    $input-height: $control-height - $uni-spacing-col-base * 2;

    page {
        background-color: #f0f0f0;
    }

    .btn {
        line-height: $input-height - 10upx;
        height: $input-height - 10upx;
        color: #fff;
        text-align: center;
        background-color: #3388ff;

    }

    .sendbtn {

        margin-left: 10upx !important;
        padding: 0px 24upx !important;

    }

    .scroller {
        flex: 1;
    }

    .emoj_box {
        flex-direction: row;
        flex-wrap: wrap;
        justify-content: space-between;
    }

    .emoj_box_img {
        font-size: 50rpx;
        width: 83rpx;
        margin-right: 10rpx;
        height: 83rpx;
        text-align: center;
        line-height: 83rpx;
    }

    .redpack .info {
        display: table;
        table-layout: fixed;
        width: 100%;
        height: 60px;
        line-height: 60px;
    }

    .redpack .info view {
        display: table-cell;
        vertical-align: middle;
        padding: 0px 0px;
        margin: 0px 0px;
    }

    .redpack .info view.icon {
        width: 55px;
        text-align: center;
    }

    .redpack .info view.showtext {
        color: #fff;
        font-size: 16px;
        ;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .redpack .info view.icon image {
        vertical-align: middle;
        width: 60rpx;
        height: 70rpx;
    }

    .redpack .title {
        height: 25px;
        line-height: 25px;
        color: #fff;
        font-size: 12px;
        border-top: #fa785e solid 1rpx;
    }

    .redpack.redpack-open .title {
        color: #fff;
        border-top: #ffd5ab solid 1px;
    }

    .redpack {
        background: rgb(246, 164, 81);
        color: #fff;
        border-radius: 8rpx;

        &:before {
            border-color: transparent $redpackBgColor transparent transparent;
        }

        &-open {
            background: #fbbc88;
            border-radius: 8rpx;

            .redpack-body-image {
                background: #fb5538;
            }

            .redpack-body-image::before {
                background: #FFF3E7;
                top: -110upx;
            }

            &:before {
                border-color: transparent #FDE1C3 transparent transparent;
            }
        }

        &-body {
            padding: 20upx;
            display: flex;
            align-items: center;

            &-image {
                background: #CD3D35;
                width: 70upx;
                height: 90upx;
                overflow: hidden;
                position: relative;
                border-radius: 6upx;

                &:before {
                    content: "";
                    display: block;
                    width: 140upx;
                    height: 140upx;
                    border-radius: 50%;
                    position: absolute;
                    top: -90upx;
                    left: 50%;
                    transform: translateX(-50%);
                    background: #FA5151;
                }

                &:after {
                    position: relative;
                    display: block;
                    content: '￥';
                    width: 28upx;
                    height: 28upx;
                    background-color: #f2523c;
                    color: #E08B34;
                    border-radius: 28upx;
                    line-height: 32upx;
                    font-size: 24upx;
                    transform: scale(.8);
                    margin: 36upx auto;
                    text-align: center;
                }
            }

            &-content {
                padding-left: 20upx;

            }
        }

        &-footer {
            font-size: 24upx;
            padding: 10upx 20upx;
            background: #fff;
            color: #999;
            border-bottom-left-radius: 12upx;
            border-bottom-right-radius: 12upx;
        }
    }

    .image:before {
        opacity: 0
    }
</style>